import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import Apply from 'src/entities/apply.entity';
import { Repository } from 'typeorm';
import { CreateApplyDto, UpdateApplyStatusDto } from './apply.dto';
import User from 'src/entities/user.entity';

@Injectable()
export class ApplyService {
  constructor(
    @InjectRepository(Apply) private applyRepository: Repository<Apply>,
    @InjectRepository(User) private userRepository: Repository<User>,
  ) {}

  // 面试邀请
  async create(createApplyDto: CreateApplyDto) {
    const apply = this.applyRepository.create(createApplyDto);
    return await this.applyRepository.save(apply);
  }

  // 获取列表
  async find(id: string) {
    const applyList = await this.applyRepository
      .createQueryBuilder('apply')
      .where('apply.userId = :id', { id })
      .orWhere('apply.friendId = :id', { id })
      .getMany();

    const applyPromise = applyList.map(async (item) => {
      const user = await this.userRepository.findOne({
        where: { id: item.userId },
        select: ['avatar', 'nickname'],
      });
      return { ...item, avatar: user.avatar, nickName: user.nickname };
    });

    return await Promise.all(applyPromise);
  }

  // 查询详细
  async findOne(id: number) {
    return await this.applyRepository.findOne({ where: { id } });
  }

  // 更新面试邀请状态
  async updateStatus(updateApplyStatusDto: UpdateApplyStatusDto) {
    const { type, userId, id, status } = updateApplyStatusDto;

    if (type === 'all') {
      this.applyRepository.update({ friendId: userId }, { status: 1 });
    } else {
      this.applyRepository.update(id, { status });
    }
  }
}
